package cn.dansj.handler.interfaces;

import cn.dansj.annotation.MarkAsApi;
import cn.dansj.annotation.InterfaceParam;
import cn.dansj.bean.CurrentThreadLocalUserInfo;
import cn.dansj.common.utils.transfer.Transformation;
import cn.dansj.handler.InterfaceHandler;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("all")
@MarkAsApi
public class ConfirmMailCaptcha extends InterfaceHandler {
    @Override
    @InterfaceParam(require = true, value = "mail", comment = "邮箱地址")
    @InterfaceParam(require = true, value = "use", comment = "用途")
    @InterfaceParam(require = true, value = "code", comment = "验证码")
    public Object execute(Map<String, Object> paramsMap) {
        Map<String, Object> checkResult = new HashMap<>();
        try {
            String mail = paramsMap.get("mail").toString();
            String use = paramsMap.get("use").toString();
            String code = paramsMap.get("code").toString();
            Map<String, Object> map = jdbcTemplate.queryForMap("select count(1) num from x_user_info where mail = ?", mail);

            if (Transformation.parseInt(map.get("num"), 0) > 0) {
                checkResult.put("confirm", false);
                checkResult.put("message", "该邮箱已被绑定");
                return checkResult;
            }

            String key = "captcha@" + mail + "@" + use;
            String redisCode = redisUtils.getString(key);
            boolean check = code.equals(redisCode);
            if (check) {
                checkResult.put("confirm", true);
                String userId = CurrentThreadLocalUserInfo.getCurrentThreadLocalUserInfo().getCacheToken().getSequence();
                int update = jdbcTemplate.update("update x_user_info set mail = ? where sequence = ?", mail, userId);
                if (update == 1) {
                    checkResult.put("message", "邮箱绑定成功");
                } else {
                    checkResult.put("message", "邮箱绑定失败");
                }
                redisUtils.delete(key);
            } else {
                checkResult.put("confirm", false);
                checkResult.put("message", "邮箱验证码错误");
            }
            return checkResult;
        } catch (Exception e) {
            checkResult.put("confirm", false);
            checkResult.put("message", "验证过程发生异常");
            return checkResult;
        }
    }
}